package com.example.fsd.service.navmenu;

import com.example.fsd.bo.NavMenuBo;
import com.example.fsd.common.result.R;
import com.example.fsd.mapper.NavMenuMapper;
import com.example.fsd.pojo.NavMenu;
import com.example.fsd.service.BaseService;
import com.example.fsd.service.navmenu.INavMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangguihong
 * @since 2024-11-19
 */
@Service
public class NavMenuServiceImpl extends ServiceImpl<NavMenuMapper, NavMenu> implements INavMenuService, BaseService {

    @Override
    public R listNavMenu() {
        List<NavMenu> list = this.list();
        List<NavMenuBo> navMenuBos = tranferListBo(list, NavMenuBo.class);
        List<NavMenuBo> parentList=navMenuBos.stream().filter(v->v.getPid()==0).collect(Collectors.toList());
        List<NavMenuBo> childrenList=navMenuBos.stream().filter(v->v.getPid()!=0).collect(Collectors.toList());
        List<NavMenuBo> navList = NavMenuBoList(parentList, childrenList);
        System.out.println(navList);
        return R.ok().put("navList",navList);
    }

    public  List<NavMenuBo> NavMenuBoList(List<NavMenuBo> parent,List<NavMenuBo> children){
        parent.stream().forEach(v->{
            List<NavMenuBo> childrenList=children.stream().filter(k->k.getPid()==v.getId()).collect(Collectors.toList());
            if(childrenList==null || childrenList.size()==0){
                v.setChildren(new ArrayList<>());
            }else {
                v.setChildren(childrenList);
                NavMenuBoList(childrenList,children);
            }
        });
        return parent;

    }
    @Override
    public R updateNavMenu(List<NavMenu> navMenus) {
        /* 先分离出父菜单和子菜单 */
        List<NavMenu> parentMenus = navMenus.stream()
                .filter(menu -> menu.getPid() == 0)
                .collect(Collectors.toList());

        List<NavMenu> childMenus = navMenus.stream()
                .filter(menu -> menu.getPid() != 0)
                .collect(Collectors.toList());
        /* 更新父菜单 */
        if (!parentMenus.isEmpty()) {
            this.updateBatchById(parentMenus);
        }
        /* 更新子菜单 */
        if (!childMenus.isEmpty()) {
            this.updateBatchById(childMenus);
        }

        return R.ok();
    }

    @Override
    public R addNavMenu(NavMenu navMenu) {
        boolean save = this.save(navMenu);
        if (save) {
            return R.ok();
        } else {
            return R.error("新增失败");
        }
    }
}
